<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.2" />






<meta name="description" content="1. 什么是 Server-Sent Events1.1. Server-Sent Events 简介SSE（Server-Sent Event，服务端推送事件）是一种允许服务端向客户端推送新数据的 HTML5 技术。与由客户端每隔几秒从服务端轮询拉取新数据相比，这是一种更优的解决方案。 1.2. SSE 与 WebSocket 相比同为浏览器推送技术，相较于 WebSocket 而言，Serve">
<meta property="og:type" content="article">
<meta property="og:title" content="HTML5 之 Server-Sent Events™">
<meta property="og:url" content="http://xiezixi.oschina.io/2018/06/01/HTML5-SSE/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="1. 什么是 Server-Sent Events1.1. Server-Sent Events 简介SSE（Server-Sent Event，服务端推送事件）是一种允许服务端向客户端推送新数据的 HTML5 技术。与由客户端每隔几秒从服务端轮询拉取新数据相比，这是一种更优的解决方案。 1.2. SSE 与 WebSocket 相比同为浏览器推送技术，相较于 WebSocket 而言，Serve">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://xiezixi.oschina.io/blog/images/sse2.png">
<meta property="og:image" content="http://xiezixi.oschina.io/blog/images/sse1.png">
<meta property="og:updated_time" content="2018-06-01T08:51:10.795Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HTML5 之 Server-Sent Events™">
<meta name="twitter:description" content="1. 什么是 Server-Sent Events1.1. Server-Sent Events 简介SSE（Server-Sent Event，服务端推送事件）是一种允许服务端向客户端推送新数据的 HTML5 技术。与由客户端每隔几秒从服务端轮询拉取新数据相比，这是一种更优的解决方案。 1.2. SSE 与 WebSocket 相比同为浏览器推送技术，相较于 WebSocket 而言，Serve">
<meta name="twitter:image" content="http://xiezixi.oschina.io/blog/images/sse2.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xiezixi.oschina.io/2018/06/01/HTML5-SSE/"/>





  <title>HTML5 之 Server-Sent Events™ | 个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">曦瓜皮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xiezixi.oschina.io/blog/2018/06/01/HTML5-SSE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="曦瓜皮">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">HTML5 之 Server-Sent Events™</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-01T16:51:10+08:00">
                2018-06-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/HTML5/" itemprop="url" rel="index">
                    <span itemprop="name">HTML5</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-什么是-Server-Sent-Events"><a href="#1-什么是-Server-Sent-Events" class="headerlink" title="1. 什么是 Server-Sent Events"></a>1. 什么是 Server-Sent Events</h2><h3 id="1-1-Server-Sent-Events-简介"><a href="#1-1-Server-Sent-Events-简介" class="headerlink" title="1.1. Server-Sent Events 简介"></a>1.1. Server-Sent Events 简介</h3><p>SSE（Server-Sent Event，服务端推送事件）是一种允许服务端向客户端推送新数据的 HTML5 技术。与由客户端每隔几秒从服务端轮询拉取新数据相比，这是一种更优的解决方案。</p>
<h3 id="1-2-SSE-与-WebSocket-相比"><a href="#1-2-SSE-与-WebSocket-相比" class="headerlink" title="1.2. SSE 与 WebSocket 相比"></a>1.2. SSE 与 WebSocket 相比</h3><p>同为浏览器推送技术，相较于 WebSocket 而言，Server-Sent Events （简称SSE）更少被人知晓，具体实践也较少。</p>
<p>原因有两点：</p>
<ul>
<li>WebSocket 比 SSE 更强大，WebSocket 在客户端和服务器之间建立了双向的实时通信。而 SSE 只支持从服务器到客户端的单向实时通信。</li>
<li>WebSocket 在浏览器方面支持更广，IE / Edge 几乎根本不支持 SSE。</li>
</ul>
<p>然而，就第一点而言，与 WebSocket 相比，SSE 也有独特的优势：</p>
<ul>
<li>SSE 的浏览器端实现内置断线重连和消息追踪的功能，WebSocket 也能实现，但是不在协议设计范围内，需要手动处理。</li>
<li>SSE 实现简单，完全复用现有的 HTTP 协议，而 WebSocket 是相对独立于 HTTP 的一套标准，跨平台实现较为复杂。</li>
</ul>
<p>综合而言，相较于 WebSocket，SSE 基于 HTTP 协议单向工作，更加简单，易用。在一些情况下，使用 SSE 反而是更好的选择。</p>
<h3 id="1-3-协议实现"><a href="#1-3-协议实现" class="headerlink" title="1.3. 协议实现"></a>1.3. 协议实现</h3><p>SSE 协议很简单，本质上是一个客户端发起的 HTTP Get 请求，服务器在接到该请求后，返回 200 OK 状态，同时附带以下 Headers</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Content-Type: text/event-stream</span><br><span class="line">Cache-Control: no-cache</span><br><span class="line">Connection: keep-alive</span><br></pre></td></tr></table></figure>
<ul>
<li>SSE 的 MIME Type 规定为 text/event-stream</li>
<li>SSE 肯定不允许缓存</li>
<li>SSE 是一个一直打开的 TCP 连接，所以 Connection 为 Keep-Alive</li>
</ul>
<p>之后，服务器保持连接，在 Body 中持续发送文本流，以实现实时消息推送。</p>
<h3 id="1-4-浏览器兼容性"><a href="#1-4-浏览器兼容性" class="headerlink" title="1.4. 浏览器兼容性"></a>1.4. 浏览器兼容性</h3><p><a href="https://caniuse.com/#search=Server-sent%20events" target="_blank" rel="noopener">Server-Sent Event 浏览器兼容性</a></p>
<h2 id="2-text-event-stream-文本流"><a href="#2-text-event-stream-文本流" class="headerlink" title="2. text/event-stream 文本流"></a>2. text/event-stream 文本流</h2><h3 id="2-1-基础格式"><a href="#2-1-基础格式" class="headerlink" title="2.1 基础格式"></a>2.1 基础格式</h3><p>文本流基础格式如下，以行为单位的，以冒号分割 Field 和 Value，每行结尾为 <code>\n</code>，每行会Trim掉前后空字符，因此 <code>\r\n</code> 也可以。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">field: value\n</span><br></pre></td></tr></table></figure>
<p>注释以冒号打头，格式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">: This is a comment\n</span><br></pre></td></tr></table></figure>
<h3 id="2-2-事件"><a href="#2-2-事件" class="headerlink" title="2.2. 事件"></a>2.2. 事件</h3><p>事件之间用 额外的<code>\n</code> 隔断（即<code>\n\n</code>）， 每个事件既可以为单行，也可为多行。</p>
<h4 id="2-2-1-事件分类"><a href="#2-2-1-事件分类" class="headerlink" title="2.2.1. 事件分类"></a>2.2.1. 事件分类</h4><p>下面所示是两个由单行组成的事件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">data:  message\n\n</span><br><span class="line">data:  message2\n\n</span><br></pre></td></tr></table></figure>
<p>而这一个是由多行组成的一个事件，更加易读：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">data: &#123;\n</span><br><span class="line">data: &quot;foo&quot;: &quot;bar&quot;,\n</span><br><span class="line">data: &quot;baz&quot;, 555\n</span><br><span class="line">data: &#125;\n\n</span><br></pre></td></tr></table></figure>
<h4 id="2-2-2-事件唯一标示"><a href="#2-2-2-事件唯一标示" class="headerlink" title="2.2.2. 事件唯一标示"></a>2.2.2. 事件唯一标示</h4><p>每一个事件可以指定 ID</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">id: msg1\n</span><br><span class="line">data: message\n\n</span><br></pre></td></tr></table></figure>
<p>浏览器会一直跟踪最近的事件 ID，如果发生了重连，浏览器会把最近接收到的事件 ID 放入 HTTP Header <code>Last-Event-ID</code> 中，作为一种简单的同步机制。</p>
<h4 id="2-2-3-命名事件"><a href="#2-2-3-命名事件" class="headerlink" title="2.2.3. 命名事件"></a>2.2.3. 命名事件</h4><p>除了 ID 唯一标示一个事件之外，也可以通过命名的方式，区分一组类型的事件。默认情况下，事件会被命名为 <code>message</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">event: foo\n</span><br><span class="line">data: a foo event\n\n</span><br><span class="line">data: an unnamed event\n\n</span><br><span class="line">data: a bar event\n</span><br><span class="line">event: bar\n\n</span><br></pre></td></tr></table></figure>
<p>上面的例子实际上是三个事件，第一个事件命名为 “foo”，第二个事件没有命名，第三个事件命名为”bar”。可以看出，在一个事件内部，”event” 可以放在前面，也可以放在末尾。</p>
<h4 id="2-2-4-重连时间"><a href="#2-2-4-重连时间" class="headerlink" title="2.2.4. 重连时间"></a>2.2.4. 重连时间</h4><p>一般情况下，连接中断的时候，客户端会在 3 秒内进行重连，这个时间也可以由服务器来指定</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">retry: 10000\n</span><br></pre></td></tr></table></figure>
<h2 id="3-客户端-API"><a href="#3-客户端-API" class="headerlink" title="3. 客户端 API"></a>3. 客户端 API</h2><h3 id="3-1-检测-SSE-支持"><a href="#3-1-检测-SSE-支持" class="headerlink" title="3.1. 检测 SSE 支持"></a>3.1. 检测 SSE 支持</h3><p>一般可以通过检测 EventSource 对象是否存在来判定当前浏览器是否支持 SSE</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">supportsSSE</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> !!<span class="built_in">window</span>.EventSource;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-2-连接事件源"><a href="#3-2-连接事件源" class="headerlink" title="3.2. 连接事件源"></a>3.2. 连接事件源</h3><p>直接创建 EventSource 对象即可，创建完成后，浏览器会及时打开。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> EventSource(url);</span><br></pre></td></tr></table></figure>
<p>事件源连接后会发送 <code>open</code> 事件，可以用两种方式监听:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">source.onopen = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// handle open event</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">source.addEventListener(<span class="string">"open"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// handle open event</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<h3 id="3-3-接收事件"><a href="#3-3-接收事件" class="headerlink" title="3.3. 接收事件"></a>3.3. 接收事件</h3><p>和上面类似，有两种方式可以接收事件。浏览器会自动把一个消息中的多个分段拼接成一个完整的字符串，因此，可以轻松地在这里使用 JSON 序列化和反序列化处理。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">source.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> data = event.data;</span><br><span class="line">  <span class="keyword">var</span> origin = event.origin;</span><br><span class="line">  <span class="keyword">var</span> lastEventId = event.lastEventId;</span><br><span class="line">  <span class="comment">// handle message</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">source.addEventListener(<span class="string">"message"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> data = event.data;</span><br><span class="line">  <span class="keyword">var</span> origin = event.origin;</span><br><span class="line">  <span class="keyword">var</span> lastEventId = event.lastEventId;</span><br><span class="line">  <span class="comment">// handle message</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<h3 id="3-4-命名事件"><a href="#3-4-命名事件" class="headerlink" title="3.4. 命名事件"></a>3.4. 命名事件</h3><p>命名事件不会由 <code>message</code> 监听触发，而是使用独立的监听：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">source.addEventListener(<span class="string">"foo"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> data = event.data;</span><br><span class="line">  <span class="keyword">var</span> origin = event.origin;</span><br><span class="line">  <span class="keyword">var</span> lastEventId = event.lastEventId;</span><br><span class="line">  <span class="comment">// handle message</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<h3 id="3-5-错误处理"><a href="#3-5-错误处理" class="headerlink" title="3.5. 错误处理"></a>3.5. 错误处理</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">source.onerror = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// handle error event</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">source.addEventListener(<span class="string">"error"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// handle error event</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<h3 id="3-6-主动断开连接"><a href="#3-6-主动断开连接" class="headerlink" title="3.6. 主动断开连接"></a>3.6. 主动断开连接</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">source.close();</span><br></pre></td></tr></table></figure>
<h3 id="3-7-连接状态"><a href="#3-7-连接状态" class="headerlink" title="3.7. 连接状态"></a>3.7. 连接状态</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">switch</span> (source.readyState) &#123;</span><br><span class="line">  <span class="keyword">case</span> EventSource.CONNECTING:</span><br><span class="line">    <span class="comment">// do something</span></span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">case</span> EventSource.OPEN:</span><br><span class="line">    <span class="comment">// do something</span></span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">case</span> EventSource.CLOSED:</span><br><span class="line">    <span class="comment">// do something</span></span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">default</span>:</span><br><span class="line">    <span class="comment">// this never happens</span></span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-服务端实现"><a href="#4-服务端实现" class="headerlink" title="4. 服务端实现"></a>4. 服务端实现</h2><p>要在服务器端实现 SSE 必须要注意，SSE 为每个用户保持了一个 TCP 连接，这就意味着Apache 之类的基于 线程/进程 的服务器引擎不适合这个工作。而 Node.js 绝对是最佳选择。</p>
<h2 id="5-简单实例"><a href="#5-简单实例" class="headerlink" title="5. 简单实例"></a>5. 简单实例</h2><h3 id="5-1-服务端-server-js"><a href="#5-1-服务端-server-js" class="headerlink" title="5.1. 服务端 server.js"></a>5.1. 服务端 server.js</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>)</span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"></span><br><span class="line">http.createServer(<span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> fileName = <span class="string">"."</span> + req.url;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (fileName === <span class="string">"./stream"</span>) &#123;</span><br><span class="line">        res.writeHead(<span class="number">200</span>, &#123;</span><br><span class="line">            <span class="string">"Content-Type"</span>:<span class="string">"text/event-stream;charset=utf-8"</span>,</span><br><span class="line">            <span class="string">"Cache-Control"</span>:<span class="string">"no-cache"</span>,</span><br><span class="line">            <span class="string">"Connection"</span>:<span class="string">"keep-alive"</span>,</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        res.write(<span class="string">"retry: 10000\n"</span>);</span><br><span class="line">        res.write(<span class="string">"event: connecttime\n"</span>);</span><br><span class="line">        res.write(<span class="string">": This is a comment\n"</span>);</span><br><span class="line">        res.write(<span class="string">"id: "</span> + (<span class="keyword">new</span> <span class="built_in">Date</span>()).valueOf() + <span class="string">"\n"</span>);</span><br><span class="line">        res.write(<span class="string">"data: "</span> + (<span class="keyword">new</span> <span class="built_in">Date</span>()) + <span class="string">"\n\n"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">const</span> interval = setInterval(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            res.write(<span class="string">"id: "</span> + (<span class="keyword">new</span> <span class="built_in">Date</span>()).valueOf() + <span class="string">"\n"</span>);</span><br><span class="line">            res.write(<span class="string">"data: "</span> + (<span class="keyword">new</span> <span class="built_in">Date</span>()) + <span class="string">"\n\n"</span>);</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">        req.connection.addListener(<span class="string">"close"</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            clearInterval(interval);</span><br><span class="line">        &#125;, <span class="literal">false</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        fs.readFile(<span class="string">'./index.html'</span>, <span class="string">'utf8'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err, html</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (err) &#123;</span><br><span class="line">                <span class="built_in">console</span>.error(err);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            res.end(html);</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;).listen(<span class="number">9999</span>);</span><br></pre></td></tr></table></figure>
<h3 id="5-2-客户端"><a href="#5-2-客户端" class="headerlink" title="5.2. 客户端"></a>5.2. 客户端</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>SSE<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">    (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> source = <span class="keyword">new</span> EventSource(<span class="string">'/stream'</span>)</span></span><br><span class="line"><span class="javascript">        source.onopen = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(event);</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">        source.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(event);</span></span><br><span class="line"><span class="javascript">            <span class="built_in">document</span>.body.innerHTML = event.data;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">        source.onerror = <span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(error)</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">    &#125;)()</span></span><br><span class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="5-3-请求查看"><a href="#5-3-请求查看" class="headerlink" title="5.3. 请求查看"></a>5.3. 请求查看</h3><p><img src="http://xiezixi.oschina.io/blog/images/sse2.png" alt="请求查看2"></p>
<p><img src="http://xiezixi.oschina.io/blog/images/sse1.png" alt="请求查看1"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/06/01/HTML5-WebStorage/" rel="next" title="HTML5 之 WebStorage™">
                <i class="fa fa-chevron-left"></i> HTML5 之 WebStorage™
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/06/01/HTML5-WebWorker/" rel="prev" title="HTML5 之 Web Worker">
                HTML5 之 Web Worker <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.jpg"
               alt="曦瓜皮" />
          <p class="site-author-name" itemprop="name">曦瓜皮</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-什么是-Server-Sent-Events"><span class="nav-number">1.</span> <span class="nav-text">1. 什么是 Server-Sent Events</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-Server-Sent-Events-简介"><span class="nav-number">1.1.</span> <span class="nav-text">1.1. Server-Sent Events 简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-SSE-与-WebSocket-相比"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. SSE 与 WebSocket 相比</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-协议实现"><span class="nav-number">1.3.</span> <span class="nav-text">1.3. 协议实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-浏览器兼容性"><span class="nav-number">1.4.</span> <span class="nav-text">1.4. 浏览器兼容性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-text-event-stream-文本流"><span class="nav-number">2.</span> <span class="nav-text">2. text/event-stream 文本流</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-基础格式"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 基础格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-事件"><span class="nav-number">2.2.</span> <span class="nav-text">2.2. 事件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-事件分类"><span class="nav-number">2.2.1.</span> <span class="nav-text">2.2.1. 事件分类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-2-事件唯一标示"><span class="nav-number">2.2.2.</span> <span class="nav-text">2.2.2. 事件唯一标示</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-3-命名事件"><span class="nav-number">2.2.3.</span> <span class="nav-text">2.2.3. 命名事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-4-重连时间"><span class="nav-number">2.2.4.</span> <span class="nav-text">2.2.4. 重连时间</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-客户端-API"><span class="nav-number">3.</span> <span class="nav-text">3. 客户端 API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-检测-SSE-支持"><span class="nav-number">3.1.</span> <span class="nav-text">3.1. 检测 SSE 支持</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-连接事件源"><span class="nav-number">3.2.</span> <span class="nav-text">3.2. 连接事件源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-接收事件"><span class="nav-number">3.3.</span> <span class="nav-text">3.3. 接收事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-命名事件"><span class="nav-number">3.4.</span> <span class="nav-text">3.4. 命名事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5-错误处理"><span class="nav-number">3.5.</span> <span class="nav-text">3.5. 错误处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6-主动断开连接"><span class="nav-number">3.6.</span> <span class="nav-text">3.6. 主动断开连接</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7-连接状态"><span class="nav-number">3.7.</span> <span class="nav-text">3.7. 连接状态</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-服务端实现"><span class="nav-number">4.</span> <span class="nav-text">4. 服务端实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-简单实例"><span class="nav-number">5.</span> <span class="nav-text">5. 简单实例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-服务端-server-js"><span class="nav-number">5.1.</span> <span class="nav-text">5.1. 服务端 server.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-客户端"><span class="nav-number">5.2.</span> <span class="nav-text">5.2. 客户端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-请求查看"><span class="nav-number">5.3.</span> <span class="nav-text">5.3. 请求查看</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">曦瓜皮</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  

  

  

  

  

</body>
</html>
